﻿using AutoMapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Role;
using System.Data.SqlTypes;
using System.Transactions;
using Microsoft.Extensions.Logging;
using RBAC.Domain.RBAC;

namespace RBAC.Write.Api.Application.Handler.Role
{
    public class CreateRoleHandler : IRequestHandler<CreateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<RolePermissionModel> rolePermissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateRoleHandler> logger;

        public CreateRoleHandler(IBaseRepository<RoleModel> roleRepository, IBaseRepository<RolePermissionModel> rolePermissionRepository, IMapper mapper, ILogger<CreateRoleHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.rolePermissionRepository = rolePermissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            
            try
            {
                logger.LogInformation("开始创建角色: {RoleName}", request.RoleName);
                
                // 1. 数据验证
                if (string.IsNullOrWhiteSpace(request.RoleName))
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "角色名称不能为空";
                    logger.LogWarning("角色名称验证失败: {RoleName}", request.RoleName);
                    return Task.FromResult(res);
                }
                
                // 2. 检查角色名是否已存在
                var existingRole = roleRepository.GetFirstOrDefault("RoleName = @RoleName AND IsDeleted = false", new { RoleName = request.RoleName });
                if (existingRole != null)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "角色名称已存在";
                    logger.LogWarning("角色名称已存在: {RoleName}", request.RoleName);
                    return Task.FromResult(res);
                }
                
                var role = mapper.Map<RoleModel>(request);
                
                // 设置默认值
                role.CreateTime = DateTime.Now;
                role.IsDeleted = false;
                
                logger.LogInformation("角色映射完成: RoleName={RoleName}, CreateTime={CreateTime}", 
                    role.RoleName, role.CreateTime);
                
                using (TransactionScope tran = new TransactionScope())
                {
                    try
                    {
                        // 3. 创建角色
                        var roleId = roleRepository.Create(role);
                        if (roleId <= 0)
                        {
                            throw new InvalidOperationException("角色创建失败，返回的ID无效");
                        }
                        logger.LogInformation("角色创建成功，ID: {RoleId}", roleId);
                        
                        // 4. 批量创建角色权限关联（使用Dapper批量操作）
                        if (request.PermissionIds != null && request.PermissionIds.Any())
                        {
                            logger.LogInformation("开始批量创建角色权限关联，权限数量: {PermissionCount}", request.PermissionIds.Count());
                            
                            // 准备批量插入的数据
                            var rolePermissions = request.PermissionIds.Select(permissionId => new RolePermissionModel
                            {
                                RoleId = roleId,
                                PermissionId = permissionId,
                                IsDeleted = false,
                                CreateTime = DateTime.Now
                            }).ToList();
                            
                            // 使用批量插入方法
                            var batchResult = rolePermissionRepository.CreateBatch(rolePermissions);
                            logger.LogInformation("角色权限关联批量创建完成: 预期 {ExpectedCount} 条，实际创建 {ActualCount} 条", 
                                rolePermissions.Count, batchResult);
                            
                            // 严格验证批量插入结果
                            if (batchResult != rolePermissions.Count)
                            {
                                throw new InvalidOperationException($"批量创建角色权限关联失败: 预期 {rolePermissions.Count} 条，实际创建 {batchResult} 条");
                            }
                        }
                        else
                        {
                            logger.LogInformation("没有指定权限ID，跳过角色权限关联创建");
                        }
                        
                        tran.Complete();
                        
                        res.Code = APIEnums.Success;
                        res.Msg = "角色创建成功";
                        res.Data = roleId;
                        
                        logger.LogInformation("角色 {RoleName} 创建完成，ID: {RoleId}", request.RoleName, roleId);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "创建角色过程中发生错误: {Message}", ex.Message);
                        res.Code = APIEnums.Error;
                        res.Msg = "添加角色失败";
                        res.Data = 0;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "创建角色失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "添加角色失败";
                res.Data = 0;
            }
            
            return Task.FromResult(res);
        }
    }
}
